uniform float sunAzimuth;
uniform float sunElevation;
uniform float skyBrightness;

varying vec2 texCoord;

const float EARTH_RADIUS = 6378137.0; // meters
const float ATMOSPHERE_RADIUS = 6408137.0; // meters 

vec3 azimuthElevToVec(in float azimuth, in float elevation)
{
	vec3 result;
	result.x = cos(azimuth);
	result.y = sin(azimuth);
	result.z = sin(elevation);
	return result;
}

vec3 intersectionRaySphere(in vec3 rayDir, in vec3 rayOrig, in float sphereRadius)
{
	float B = dot(rayOrig, rayDir);
	float C = dot(rayOrig, rayOrig) - sphereRadius;
	float D = B*B - C;
	if(D > 0.0) 
		return(-B - sqrt(D) * rayDir);
	else
		return 1.0/0.00000000000001 * rayDir;
}

void main()
{
	float pointAzimuth = texCoord.s;
	float pointElevation = texCoord.t;
	{
		// diffuse illumination of the atmosphere 
		vec3 pointVector = azimuthElevToVec(pointAzimuth,pointElevation);
		vec3 sunVector = azimuthElevToVec(sunAzimuth,sunElevation);

		//vec3 centerPoint = vec3(0,0,0);
		vec3 cameraPoint = vec3(0,0,EARTH_RADIUS);
		vec3 atmosphPoint = intersectionRaySphere(pointVector, cameraPoint, ATMOSPHERE_RADIUS);
		vec3 atmosphNormal = normalize(atmosphPoint);

		float primaryLength = length(cameraPoint - atmosphPoint);
		vec3 goThruCoeffs = (vec3(1.0)-vec3(0.077,0.105,0.145)) /(primaryLength /ATMOSPHERE_RADIUS);
		// direct atmosphere illumination
		float sunIntensity = skyBrightness * 10000.0;
		vec3 directColor= goThruCoeffs* sunIntensity * max(0.0,dot(atmosphNormal, normalize(sunVector)))   ;

		// scattered atmosphere illumination

		vec3 secondaryAtmPoint = intersectionRaySphere(atmosphPoint +  0.0001* sunVector,sunVector, ATMOSPHERE_RADIUS);
		float secondaryLength;
		if(length(secondaryAtmPoint) > ATMOSPHERE_RADIUS + 1000.0)
			secondaryLength = primaryLength;
		else
			secondaryLength = primaryLength + length(atmosphPoint-secondaryAtmPoint);

		vec3 indirectColor = sunIntensity * (vec3(0.077,0.105,0.145) / (secondaryLength /ATMOSPHERE_RADIUS/10.0));

		gl_FragColor.rgb = directColor + indirectColor;
	}
	
	gl_FragColor.a = 1.0;
}





